#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

pthread_mutex_t g_lock1;
pthread_mutex_t g_lock2;
void *MyThreadStartA(void *arg)
{
    (void)arg;
    pthread_mutex_lock(&g_lock1);
    sleep(3);//等待线程B拿到锁2,如果不等待,线程A继续执行可能先会拿到锁2，
            //不能保证线程B先拿到锁2,这样线程A拿完锁1和锁2就return了
    pthread_mutex_lock(&g_lock2);
    return NULL;
}
void *MyThreadStartB(void *arg)
{
    (void)arg;
    pthread_mutex_lock(&g_lock2);
    sleep(3);  //等待线程A拿到锁1

    pthread_mutex_lock(&g_lock1);
    return NULL;
}
int main()
{
    pthread_mutex_init(&g_lock1,NULL);
    pthread_mutex_init(&g_lock2,NULL);
    pthread_t tid;
    int ret = pthread_create(&tid, NULL, MyThreadStartA, NULL);
    if(ret < 0)
    {
        perror("pthread_create");
        return 0;
    }

    ret = pthread_create(&tid, NULL, MyThreadStartB, NULL);
    if(ret < 0)
    {
        perror("pthread_create");
        return 0;
    }

    while(1) //为了不让主线程退出
    {
        sleep(1);
    }

    pthread_mutex_destroy(&g_lock1);
    pthread_mutex_destroy(&g_lock2);
    return 0;
}
